from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5
from Crypto.Signature import PKCS1_v1_5 as Signature_pkcs1_v1_5
import base64
from Crypto.Hash import MD5
import json
import requests
import time

headers = {"X-User-Token":"756283292c03bd29dbf8a721f5ca26bc", "content-type":"application/json"}

# 告警计数
def count_alert_history (dict_in_list):
    new_list = []
    index = 0
    for i in dict_in_list:
        i = str(i)
        new_list.append(i)
    # print(type(new_list[0]))
    new_list = list(set(new_list))
    for i in new_list:
        new_list[index] = eval(i)
        new_list[index]["count"] = dict_in_list.count(new_list[index])
        index += 1
    return new_list

# 告警统计
def get_p1_alarm(cycle, alarm_grade):
    """
    cycle:时间周期
    alarm_grade:告警级别
    """
    keshi_turn = {
        "app_web":"前端应用研发室",
        "basic":"流量运营研发室",
        "beisheng":"倍升公司",
        "bigdata":"大数据",
        "framework":"架构室",
        "fund_deal":"资金交易组",
        "operation":"运维安全室",
        "riskone":"风控研发一室",
        "risktwo":"风控研发二室",
        "taichcao":"太潮",
        "SMY":"根节点"
    }

    etime = int(time.time())   # 结束时间
    stime = etime - cycle*24*3600  # 开始时间
    params = {"etime":etime, "limit":20000, "p":1, "nodepath":"SMY.information technology", "priorities":alarm_grade, "stime":stime, "type":"alert"}
    ret = requests.get("https://nightingale.smyoa.com/api/mon/event/his", headers=headers, params=params).text
    alert_history_list = json.loads(ret)['dat']['list']

    alert_history_list = list(filter(lambda x:"已发送" in x["status"], alert_history_list))
    index = 0
    for alert_history in alert_history_list:
        alert_history = {x: alert_history[x] for x in alert_history.keys() if x ==  "sname" or x == "node_path" or x == "endpoint"}
        alert_history_list[index] = alert_history
        index += 1
    # 计数，所有字段完全一样时去重计数
    alert_history_list = count_alert_history(alert_history_list)
    
    final_ret = {}
    for alert_history in alert_history_list:
        # print(alert_history)
        keshi = alert_history['node_path'].split('.')[2] if len(alert_history['node_path'].split('.')) >= 3 else alert_history['node_path'].split('.')[0]
        # print(alert_history, keshi)
        if keshi_turn[keshi] in final_ret:
            final_ret[keshi_turn[keshi]].append(alert_history)
        else:
            final_ret[keshi_turn[keshi]] = [alert_history]
    return final_ret


def get_keys(filename):
    with open(filename, 'r') as f:
        key = f.read()
    return key

# 加密函数
def encrypt_rsa(data, key):
    key = RSA.import_key(key)
    cipher_rsa = Cipher_pkcs1_v1_5.new(key) # 初始化一个加密器
    data = data.encode('utf-8')
    ##### 分段加密
    lenth = len(data)
    if lenth < 50:
        encrypt_data = cipher_rsa.encrypt(data)
    else:
        res = []
        for i in range(0, len(data), 50): 
            enc_tmp = cipher_rsa.encrypt(data[i:i+50])
            res.append(enc_tmp)
        encrypt_data = b''.join(res)
    return base64.b64encode(encrypt_data).decode()
    # return encrypt_data

# 解密函数
def  decrypt_rsa(data, key):
    key  = RSA.import_key(key)
    cipher_rsa  = Cipher_pkcs1_v1_5.new(key)
    # decrypt_data = cipher_rsa.decrypt(data, "no")
    res = []
    for i in  range(0,  len(data), 128):
        enc_tmp = cipher_rsa.decrypt(data[i:i+128], "no")
        res.append(enc_tmp)
    decrypt_data = b''.join(res)
    return  decrypt_data

# 暂时不需要签名
def sign_pm(data, key):
    key = RSA.import_key(key)
    digest = MD5.new(data.encode('utf-8'))
    signature = base64.b64encode(Signature_pkcs1_v1_5.new(key).sign(digest))
    return signature.decode()

# 提交工单信息
def report_to_pm(data, pub_key_pm, prikey):
    data = json.dumps(data)
    signs = sign_pm(data, prikey)
    url = "http://192.168.20.203:8089/pts-oms/workSheet/createWorkSheetWithDefinition"
    t = {"sign":signs, "params":data}
    t = json.dumps(t)
    params = {"reqSystem":"nightingale", "cipherParams":encrypt_rsa(t, pub_key_pm)}
    params = json.dumps(params)
    headers = {"content-type":"application/json"}
    ret_report = requests.post(url, data=params, headers=headers).text

    print(ret_report)



if __name__ == "__main__":
    alarm_infos = get_p1_alarm(1, "1")
    if alarm_infos:
        for i in alarm_infos.keys():
            if i == "倍升" or i == "根节点":
                continue
            else:
                info = [str(detail) for detail in alarm_infos[i]]
                info = "<br>".join(info)
                data = {"title":"P1告警信息工单", "typeCode":1, "dutyDepartment":i,"content":info, "level":"P1", "sourceSystem":"nightingale"}
                print(data)

        # data = {"title":"test工单", "typeCode":1, "dutyDepartment":"运维安全室",
        #     "content":"级别状态：P3 恢复（聚合）\
        #     <br>策略名称：测试\
        #     <br>告警设备：172.18.17.5\
        #     <br>挂载节点：\
        #     <br>172.18.17.5 - sz.wg1.pve.prd.cbs-rls.host01 - SMY.information technology.basic.core.cbs-core.wg\
        #     <br>172.18.17.5 - sz.wg1.pve.prd.cbs-rls.host01 - SMY.information technology.basic.core.rls-core.wg\
        #     <br>172.18.17.5 - sz.wg1.pve.prd.cbs-rls.host01 - SMY.information technology.治愈测试\
        #     <br>监控指标：disk.bytes.used.percent\
        #     <br>指标标签：mount=[/boot,/,/data]\
        #     <br>当前值：disk.bytes.used.percent: 11.428475576501334\
        #     <br>报警说明： disk.bytes.used.percent(all,30s) &gt;= 100\
        #     <br>触发时间：2021-03-29 16:33:00\
        #     <br>报警详情：http://nightingale.smyoa.com/mon/history/his/2308925", "level":"P1", "sourceSystem":"nightingale"}


                pub_key_pm = get_keys("D:\py文件\py脚本\pubkey_pm.txt") # pm的公钥
                prikey = get_keys("D:\py文件\py脚本\prikey.txt") # 私钥
                report_to_pm(data, pub_key_pm, prikey)